package com.example.pei.ithinklearnt.view.activity;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

import com.example.pei.ithinklearnt.AppApplication;
import com.example.pei.ithinklearnt.R;
import com.example.pei.ithinklearnt.bean.AddFriendMessage;
import com.example.pei.ithinklearnt.bean.UserInfo;
import com.example.pei.ithinklearnt.model.UserModel;
import com.example.pei.ithinklearnt.view.base.BaseActivity;
import com.example.pei.ithinklearnt.view.fragments.PersonalFragment;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.bmob.newim.BmobIM;
import cn.bmob.newim.bean.BmobIMConversation;
import cn.bmob.newim.bean.BmobIMMessage;
import cn.bmob.newim.bean.BmobIMUserInfo;
import cn.bmob.newim.core.BmobIMClient;
import cn.bmob.newim.core.ConnectionStatus;
import cn.bmob.newim.listener.MessageSendListener;
import cn.bmob.v3.BmobUser;
import cn.bmob.v3.exception.BmobException;

import static com.example.pei.ithinklearnt.utils.ImageLoaderUtil.displayImage;
import static com.example.pei.ithinklearnt.utils.ImageLoaderUtil.getPhotoImageOption;

public class UserInfoActivity0 extends BaseActivity {


    @BindView(R.id.btn_chat)
    Button button_chat;
    @BindView(R.id.btn_addfriend)
    Button button_addfriend;

    //用户
    UserInfo user;
    //用户信息
    BmobIMUserInfo info;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_user_info0);
        Bundle bundle=getBundle();
        UserInfo infoo=(UserInfo)bundle.getSerializable("u");
        int pos=bundle.getInt("pos",0);

        //必需继承FragmentActivity,嵌套fragment只需要这行代码
        getSupportFragmentManager()
                .beginTransaction()
                .replace(R.id.container, PersonalFragment.newInstance(infoo,pos))
                .commitAllowingStateLoss();

        //用户
        user = (UserInfo) getIntent().getBundleExtra(getPackageName()).getSerializable("u");
        if (user.getObjectId().equals(AppApplication.getCurrentUser().getObjectId())) {//用户为登录用户
            button_chat.setVisibility(View.GONE);
            button_addfriend.setVisibility(View.GONE);
        } else {//用户为非登录用户
            button_addfriend.setVisibility(View.VISIBLE);
            button_chat.setVisibility(View.VISIBLE);
            if(isFriend()) {
                button_addfriend.setText("已添加");
                button_addfriend.setClickable(false);
            }else{
                button_addfriend.setText("添加好友");
                button_addfriend.setClickable(true);
            }

        }
        //构造聊天方的用户信息:传入用户id、用户名和用户头像三个参数
        info = new BmobIMUserInfo(user.getObjectId(), user.getNickName(), user.getHeadFileUrl());

    }

    @OnClick({R.id.btn_addfriend, R.id.btn_chat})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.btn_addfriend: {
                sendAddFriendMessage();
                break;
            }
            case R.id.btn_chat: {
                chat();
                break;
            }
        }
    }


    /**
     * 发送添加好友的请求
     */
    //TODO 好友管理：9.7、发送添加好友请求
    private void sendAddFriendMessage() {
        if (BmobIM.getInstance().getCurrentStatus().getCode() != ConnectionStatus.CONNECTED.getCode()) {
            toast("尚未连接IM服务器");
            return;
        }
        //TODO 会话：4.1、创建一个暂态会话入口，发送好友请求
        BmobIMConversation conversationEntrance = BmobIM.getInstance().startPrivateConversation(info, true, null);
        //TODO 消息：5.1、根据会话入口获取消息管理，发送好友请求
        BmobIMConversation messageManager = BmobIMConversation.obtain(BmobIMClient.getInstance(), conversationEntrance);
        AddFriendMessage msg = new AddFriendMessage();
        UserInfo currentUser = BmobUser.getCurrentUser(UserInfo.class);
        msg.setContent("很高兴认识你，可以加个好友吗?");//给对方的一个留言信息
        Map<String, Object> map = new HashMap<>();
        map.put("name", currentUser.getNickName());//发送者姓名
        map.put("avatar", currentUser.getHeadFileUrl());//发送者的头像
        map.put("uid", currentUser.getObjectId());//发送者的uid
        msg.setExtraMap(map);
        messageManager.sendMessage(msg, new MessageSendListener() {
            @Override
            public void done(BmobIMMessage msg, BmobException e) {
                if (e == null) {//发送成功
                    toast("好友请求发送成功，等待验证");
                } else {//发送失败
                    toast("发送失败:" + e.getMessage());
                }
            }
        });
    }

    /**
     * 与陌生人聊天
     */
    private void chat() {
        if (BmobIM.getInstance().getCurrentStatus().getCode() != ConnectionStatus.CONNECTED.getCode()) {
            toast("尚未连接IM服务器");
            return;
        }
        //TODO 会话：4.1、创建一个常态会话入口，陌生人聊天
        BmobIMConversation conversationEntrance = BmobIM.getInstance().startPrivateConversation(info, null);
        Bundle bundle = new Bundle();
        bundle.putSerializable("c", conversationEntrance);
        startActivity(ChatActivity.class, bundle, false);
    }

    //查询本地是否已经是好友
    private boolean isFriend(){
        List<UserInfo> friends=UserModel.getInstance().getLocalFreinds(this);
        if(friends==null||friends.size()<=0){
            return false;
        }
        for(UserInfo info:friends){
            if(info.getUsername().equals(user.getUsername())){
                return true;
            }
        }
        return false;
    }

}
